<?php defined('SYSPATH') or die('No direct script access.');
/*
 * jQuery File Upload Plugin PHP Example 5.2.7
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://creativecommons.org/licenses/MIT/
 */

class Upload_Handler
{
    private $options;
    
    function __construct($options=null) {
        $this->options = array(
            'script_url' => '/admin/picture/delete',
            'upload_dir' => $_SERVER['DOCUMENT_ROOT'].'/uploads/picture/',
			'upload_temp_dir' => $_SERVER['DOCUMENT_ROOT'].'/uploads/temp/',
            'upload_url' => '/book/picture/image?picture_id=',
            'param_name' => 'files',
			'max_width' => 800,
			'max_height' => 800,
            'min_file_size' => 1,
            'accept_file_types' => '/.+$/i',
            'discard_aborted_uploads' => true,
            'image_versions' => array(
                // Uncomment the following version to restrict the size of
                // uploaded images. You can also add additional versions with
                // their own upload directories:
                /*
                'large' => array(
                    'upload_dir' => dirname(__FILE__).'/files/',
                    'upload_url' => dirname($_SERVER['PHP_SELF']).'/files/',
                    'max_width' => 1920,
                    'max_height' => 1200
                ),
                */
                'thumbnail' => array(
                    'upload_dir' => $_SERVER['DOCUMENT_ROOT'].'/thumbnail/picture/',
                    'upload_url' => '/book/picture/thumbnail?picture_id=',
                    'max_width' => 80,
                    'max_height' => 80
                )
            )
        );
        if ($options) {
            $this->options = array_replace_recursive($this->options, $options);
        }
    }
    
    private function get_file_objects() {
		return;
        return array_values(array_filter(array_map(
            array($this, 'get_file_object'),
            scandir($this->options['upload_dir'])
        )));
    }

    private function has_error($uploaded_file, $error) {
        if ($error) {
            return $error;
        }
        return $error;
    }

    private function handle_file_upload($booklet_id, $description, $use_thumb, $uploaded_file, $name, $size, $type, $error) {
        $file = new stdClass();

		// 文件属性
        $file->type = $type;
        $error = $this->has_error($uploaded_file, $error);
		if (!$error && $name) 
		{
			if ($uploaded_file && is_uploaded_file($uploaded_file))
			{
				$image = Kohana_Image::factory($uploaded_file);
				$extension = image_type_to_extension($image->type, FALSE);
				$file->name = UUID::v4().".".$extension;
				$file_path = $this->options['upload_dir'].$file->name;
				if (!$use_thumb)
				{
					$max_width = $this->options['max_width'];
					$max_height = $this->options['max_height'];
					if ($image->width > $max_width OR  $image->height > $max_height)
					{
						$image->resize($max_width, $max_height, Image::AUTO);
					}
				}
				$image->save($file_path, 80);
			}
			// 加入数据库
			$picture_id = $this->write_db($file, $booklet_id, $description);

			$file->size = filesize($file_path);
			$file->url = $this->options['upload_url'].$picture_id;
			foreach($this->options['image_versions'] as $version => $options) {
					$file->{$version.'_url'} = $options['upload_url'].$picture_id;
			}
		}
		else {
            $file->error = $error;
        }
        return $file;
    }
    
    public function post($booklet_id) {
        $upload = isset($_FILES[$this->options['param_name']]) ?
            $_FILES[$this->options['param_name']] : array(
                'tmp_name' => null,
                'name' => null,
                'size' => null,
                'type' => null,
				'error' => null,
            );
        $info = array();
        if (is_array($upload['tmp_name'])) {
			$desc_array = arr::get($_REQUEST, 'desc');
			$use_thumb_array = arr::get($_REQUEST, 'use_thumb');
            foreach ($upload['tmp_name'] as $index => $value) {
                $info[] = $this->handle_file_upload(
					$booklet_id,
					isset($desc_array[$index]) ? $desc_array[$index] : null,
					isset($use_thumb_array[$index]) ? $use_thumb_array[$index] : null,
                    $upload['tmp_name'][$index],
                    isset($_SERVER['HTTP_X_FILE_NAME']) ?
                        $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
                    isset($_SERVER['HTTP_X_FILE_SIZE']) ?
                        $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
                    isset($_SERVER['HTTP_X_FILE_TYPE']) ?
                        $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
                    $upload['error'][$index]
                );
				
            }
        } else {
			$desc_array = arr::get($_REQUEST, 'desc');
			$use_thumb_array = arr::get($_REQUEST, 'use_thumb');
			$info[] = $this->handle_file_upload(
				$booklet_id,
				isset($desc_array[0]) ? $desc_array[0] : null,
				isset($use_thumb_array[0]) ? $use_thumb_array[0] : null,
                $upload['tmp_name'],
                isset($_SERVER['HTTP_X_FILE_NAME']) ?
                    $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'],
                isset($_SERVER['HTTP_X_FILE_SIZE']) ?
                    $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'],
                isset($_SERVER['HTTP_X_FILE_TYPE']) ?
                    $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'],
                $upload['error']
            );
        }
        header('Vary: Accept');
        if (isset($_SERVER['HTTP_ACCEPT']) &&
            (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
            header('Content-type: application/json');
        } else {
            header('Content-type: text/plain');
        }
        echo json_encode($info);
    }
    
    public function delete() {
        $file_name = isset($_REQUEST['file']) ?
            basename(stripslashes($_REQUEST['file'])) : null;
        $file_path = $this->options['upload_dir'].$file_name;
        $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
        if ($success) {
            foreach($this->options['image_versions'] as $version => $options) {
                $file = $options['upload_dir'].$file_name;
                if (is_file($file)) {
                    unlink($file);
                }
            }
        }
        header('Content-type: application/json');
        echo json_encode($success);
    }

	private function write_db($info, $booklet_id, $description)
	{
		if (isset($info->error))
		{
			Kohana::$log->add(Log::ERROR, $info->error);
			return NULL;
		}
		else
		{
			$picture = ORM::factory("picture");
			$picture->values(array(
				'booklet_id'  => $booklet_id,
				'image'       => $info->name,
				'description' => $description,
			));
			$picture->save();
			return $picture->id;
		}
	}
}
